package db

import (
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"lidongyooo/search-bot/pkg/config"
)

var MySQL *gorm.DB

func ConnectDB() *gorm.DB {
	var err error

	// 初始化 MySQL 连接信息
	var (
		port     = config.Viper.GetString("DB.PORT")
		host     = config.Viper.GetString("DB.HOST")
		database = config.Viper.GetString("DB.DATABASE")
		username = config.Viper.GetString("DB.USERNAME")
		password = config.Viper.GetString("DB.PASSWORD")
		charset  = config.Viper.GetString("DB.CHARSET")
	)

	dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=%s&parseTime=%t&loc=%s",
		username, password, host, port, database, charset, true, "Local")
	gormConfig := mysql.Open(dsn)

	var level logger.LogLevel
	if config.Viper.GetBool("APP.DEBUG") {
		// 读取不到数据也会显示
		level = logger.Info
	} else {
		// 只有错误才会显示
		level = logger.Error
	}

	// 准备数据库连接池
	MySQL, err = gorm.Open(gormConfig, &gorm.Config{
		Logger: logger.Default.LogMode(level),
	})

	if err != nil {
		panic(err.Error())
	}
	tables()

	return MySQL
}

func tables() {
	MySQL.Exec(`
CREATE TABLE IF NOT EXISTS chats(
	id INT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
	chat_id BIGINT NOT NULL,
	name varchar(255) NOT NULL,
	type varchar(255) NOT NULL,
	status TINYINT NOT NULL,
	created_at TIMESTAMP NOT NULL,
	updated_at TIMESTAMP NOT NULL,
	UNIQUE(chat_id)
);

CREATE TABLE IF NOT EXISTS chats_messages(
	id BIGINT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
	message_id BIGINT NOT NULL,
	username varchar(255),
	text varchar(5000) NOT NULL,
	from_name varchar(255) NOT NULL,
	from_id varchar(255) NOT NULL,
	sent_at  TIMESTAMP NOT NULL,
	chat_id BIGINT NOT NULL,
	created_at TIMESTAMP NOT NULL,
	updated_at TIMESTAMP NOT NULL,
	INDEX(chat_id),
	INDEX(message_id),
	FULLTEXT text(text) WITH PARSER ngram
);

CREATE TABLE IF NOT EXISTS search_messages(
	id BIGINT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
	chat_id BIGINT NOT NULL,
	chat_name varchar(255) NOT NULL,
	message_table varchar(255) NOT NULL,
	message_ids varchar(5000) NOT NULL,
	created_at TIMESTAMP NOT NULL,
	INDEX(chat_id)
);
`)
}
